<?php

namespace App\Console\Commands\Invoice;

use App\Library\FeiShu\SendFs;
use App\Models\Invoice\InvoiceHistoryModel;
use App\Service\OpenShop\Feishu\BaseService;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;

class InvoiceScriptCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:everyDayScript {startTime=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每日汇总开票记录';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    const TYPE_1    = 1;
    const TYPE_2    = 2;
    const TYPE_3    = 3;
    const TYPE_TEXT = [
        self::TYPE_1 => "每日",
        self::TYPE_2 => "每周",
        self::TYPE_3 => "每月",
    ];

    /**
     * 文档：https://onepiece-group.feishu.cn/wiki/MiEmwPNKyiypWikngwtc9KZPnrb
     */
    public function handle()
    {
        $nowDay    = date('Y.m.d');
        $startTime = date('Y-m-d', strtotime('-1 day'));
        $endTime   = date('Y-m-d', strtotime('-1 day'));
        if (config('app.env') == 'dev') {
            $startTime = date('Y-m-d');
            $endTime   = date('Y-m-d');
        }
        $getStartTime = $this->argument('startTime');
        if ($getStartTime) {
            $startTime = $getStartTime;
            $endTime   = $getStartTime;
        }

        $title = '【每日汇总】每日开票汇总 ' . $nowDay;//标题

        self::getData(self::TYPE_1, $startTime, $endTime, $title); //昨天数据


        $week = date('w');// 每周一 查询上周数据
        if ($week == 1) {
            $startTime = date('Y-m-d', strtotime('-7 day'));  // 上周一
            $endTime   = date('Y-m-d', strtotime('-1 day'));  // 上周日
            $title     = '【每周汇总】上周开票汇总 ' . $nowDay;           //标题
            self::getData(self::TYPE_2, $startTime, $endTime, $title);
        }

        $day = date('d');// 每月1号 查询上个月数据
        if ($day == '01') {
            $startTime = date('Y-m-01', strtotime('-1 month'));  //上个月第一天
            $endTime   = date('Y-m-t', strtotime('-1 month'));   //上个月最后一天
            $title     = '【每月汇总】上月开票汇总 ' . $nowDay;              //标题
            self::getData(self::TYPE_3, $startTime, $endTime, $title);
        }

    }

    // 根据时间查询数据
    public static function getData(int $type, string $startTime, string $endTime, string $title)
    {
        $totalCount             = 0;//开票总份数
        $blueCount              = 0;//蓝字发票份数
        $redCount               = 0;//红字发票份数
        $excludingTaxAmount     = 0;//不含税金额
        $taxAmount              = 0;//税额
        $includingTaxAmount     = 0;//含税金额
        $shopCount              = 0;//开票门店数
        $goodsOrderCount        = 0;//订货订单数
        $softDecorateOrderCount = 0;//软装订单数

        $jumpUrl   = BaseService::getInvoiceListUrl(0, $startTime, $endTime);
        $dateRange = $startTime;//日期范围
        if ($type != self::TYPE_1) {
            $dateRange = $startTime . ' - ' . $endTime;
        }

        $shopIds = $goodsOrder = $softDecorateOrder = [];
        InvoiceHistoryModel::query()
            ->with(['businessRel'])
            ->where('status', InvoiceHistoryModel::STATUS_3)//发票生成成功
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime . ' 23:59:59')])
            ->get()
            ->map(
                function ($item) use (
                    &$blueCount, &$excludingTaxAmount, &$taxAmount, &$shopIds, &$includingTaxAmount,
                    &$goodsOrder, &$softDecorateOrder
                ) {
                    $blueCount++;                                                                     //蓝字发票份数
                    $excludingTaxAmount += $item->invoiceTotalAmount;                                 //不含税金额-开票总金额
                    $taxAmount          += $item->invoiceTaxTotalAmount;                              //税额-扣税的金额
                    $includingTaxAmount += $item->blueTaxValueTotal;                                  //价税合计-总金额
                    $shopIds[]          = $item->shopId;
                    $orderData          = [];
                    collect($item->businessRel)->map(
                        function ($item) use (&$orderData) {
                            $orderData[] = $item->businessId; //订货单号
                        }
                    );
                    if ($orderData) {
                        if ($item->businessType == InvoiceHistoryModel::BUSINESS_TYPE_1) {//订货
                            $goodsOrder = array_merge($goodsOrder, $orderData);
                        }
                        if ($item->businessType == InvoiceHistoryModel::BUSINESS_TYPE_2) {//软装
                            $softDecorateOrder = array_merge($softDecorateOrder, $orderData);
                        }
                    }
                }
            );
        $shopCount              = count(array_unique($shopIds));
        $goodsOrderCount        = count(array_unique($goodsOrder));
        $softDecorateOrderCount = count(array_unique($softDecorateOrder));

        $redCount = InvoiceHistoryModel::query()
            ->where('status', InvoiceHistoryModel::STATUS_5)//发票红冲成功
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime . ' 23:59:59')])
            ->count();

        $totalCount = $blueCount + $redCount;
        if (!$totalCount) {
            return;
        }

        $templateData = [
            'totalCount'             => $totalCount,                   //开票总份数
            'blueCount'              => $blueCount,                    //蓝字发票份数
            'redCount'               => $redCount,                     //红字发票份数
            'excludingTaxAmount'     => round($excludingTaxAmount, 2),  //不含税金额
            'taxAmount'              => round($taxAmount, 2), //税额
            'includingTaxAmount'     => $includingTaxAmount,           //含税金额
            'shopCount'              => $shopCount,                    //开票门店数
            'goodsOrderCount'        => $goodsOrderCount,              //订货订单数
            'softDecorateOrderCount' => $softDecorateOrderCount,       //软装订单数
            'jumpUrl'                => $jumpUrl,                      //跳转链接
            'title'                  => $title,                        //标题
            'dateRange'              => $dateRange,                    //时间范围
        ];

        $templateJson = view()->file(app_path("Remote/Feishu/FsTemplate/Invoice/InvoiceAutoScriptFsTemplate.blade.php"), $templateData)->render();

        BuildFs::newRobot(SendFs::ROBOT_INVOICE, BuildFs::MSG_TYPE_CARD)
            ->setCardContent(json_decode($templateJson, true))
            ->send();
    }
}
